package com.zhidian.edm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhidian.edm.entity.SysUserPO;
import com.zhidian.edm.entity.SysUserRolePO;
import com.zhidian.edm.mapper.SysUserMapper;
import com.zhidian.edm.mapper.SysUserRoleMapper;
import com.zhidian.edm.param.AddUserParam;
import com.zhidian.edm.param.UpdateUserParam;
import com.zhidian.edm.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhidian.edm.util.BeanConvertUtil;
import com.zhidian.edm.util.ListUtil;
import com.zhidian.edm.vo.SysUserVO;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sl
 * @since 2025-09-18
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUserPO> implements ISysUserService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public Optional<SysUserPO> findByUsername(String username) {
        SysUserPO user = sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUserPO>()
                        .eq(SysUserPO::getUserName, username)
        );
        return Optional.ofNullable(user);
    }

    @Override
    public List<SysUserVO> getUserList() {
        List<SysUserPO> sysUserPOS = sysUserMapper.selectList(null);
        return BeanConvertUtil.convertList(sysUserPOS, SysUserVO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUser(AddUserParam addUserParam) {
        SysUserPO sysUserPO = BeanConvertUtil.convert(addUserParam, SysUserPO.class);
        sysUserPO.setPassword(passwordEncoder.encode(addUserParam.getPassword()));
        int insert = sysUserMapper.insert(sysUserPO);
        if (insert <= 0) {
            throw new RuntimeException("新增用户失败");
        }

        // 3. 插入用户和角色关联
        if (addUserParam.getRoleIds() != null && !addUserParam.getRoleIds().isEmpty()) {
            List<SysUserRolePO> userRoles = addUserParam.getRoleIds().stream()
                    .map(roleId -> {
                        SysUserRolePO ur = new SysUserRolePO();
                        ur.setUserId(sysUserPO.getId());
                        ur.setRoleId(roleId);
                        return ur;
                    })
                    .collect(Collectors.toList());

            // 批量保存
            sysUserRoleMapper.insert(userRoles);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUser(UpdateUserParam updateUserParam) {
        // 1. 查询原用户
        SysUserPO dbUser = sysUserMapper.selectById(updateUserParam.getId());
        if (dbUser == null) {
            throw new RuntimeException("用户不存在");
        }

        // 2. 更新用户基本信息
        SysUserPO updateUser = new SysUserPO();
        updateUser.setId(dbUser.getId());
        updateUser.setUserName(updateUserParam.getUserName());
        updateUser.setNickName(updateUserParam.getNickName());
        sysUserMapper.updateById(updateUser);

        // 3. 更新用户角色关联（先删后加）
        sysUserRoleMapper.delete(
                new LambdaQueryWrapper<SysUserRolePO>()
                        .eq(SysUserRolePO::getUserId, updateUserParam.getId())
        );

        if (updateUserParam.getRoleIds() != null && !updateUserParam.getRoleIds().isEmpty()) {
            List<SysUserRolePO> newUserRoles = updateUserParam.getRoleIds().stream()
                    .map(roleId -> {
                        SysUserRolePO ur = new SysUserRolePO();
                        ur.setUserId(updateUserParam.getId());
                        ur.setRoleId(roleId);
                        return ur;
                    })
                    .collect(Collectors.toList());

            // 批量插入（如果没扩展批量方法，可以循环 insert）
            newUserRoles.forEach(sysUserRoleMapper::insert);
        }
    }

    @Override
    public SysUserVO getUserById(Long userId) {
        SysUserVO result = new SysUserVO();
        SysUserPO sysUserPO = sysUserMapper.selectById(userId);
        if (sysUserPO != null) {
            result = BeanConvertUtil.convert(sysUserPO, SysUserVO.class);
            List<SysUserRolePO> sysUserRolePOS = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRolePO>().eq(SysUserRolePO::getUserId, userId));
            if(CollectionUtil.isNotEmpty(sysUserRolePOS)){
                List<Long> valueList = ListUtil.toValueList(sysUserRolePOS, SysUserRolePO::getRoleId);
                result.setRoleIds(valueList);
            }
        }
        return result;
    }
}
